package com.duke.shaking.auth;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.androidquery.AQuery;
import com.duke.shaking.MainActivity;
import com.duke.shaking.R;
import com.duke.shaking.ResultCodeFactory;
import com.duke.shaking.ShakeApplication;
import com.duke.shaking.ShakeTabActivity;
import com.duke.shaking.TitleActivity;
import com.duke.shaking.net.AsyncHttpResponseWithResultHandler;
import com.duke.shaking.net.NetUtils;
import com.duke.shaking.pojo.User;
import com.duke.shaking.profile.InputBirthdayActivity;
import com.duke.shaking.profile.InputNicknameActivity;
import com.duke.shaking.profile.SetAvatarActivity;
import com.duke.shaking.utils.AppUtils;
import com.duke.shaking.utils.PrefUtils;
import com.loopj.android.http.AsyncHttpClient;

public class LoginActivity extends TitleActivity {
	
	private Activity activity;
	private AQuery aQuery;
	private String telNo;
	private String password;
	private boolean bSavePass;
	private boolean bAutoLogin;
	
	private static int RECOVER_PASSWORD = 0;

	public LoginActivity() {
		this.activity = this;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.aQuery = new AQuery(activity);
		
		// restore the user preferences
		PrefUtils prefUtils = PrefUtils.getInstance(this, this.getString(R.string.registerPref));
		bSavePass = prefUtils.getBoolean(this.getString(R.string.bSavePass), true);
		bAutoLogin = prefUtils.getBoolean(this.getString(R.string.bAutoLogin), false);
		aQuery.id(R.id.chk_save_password).getCheckBox().setChecked(bSavePass);
		aQuery.id(R.id.chk_auto_login).getCheckBox().setChecked(bAutoLogin);
		
		if (bSavePass) {
			prefUtils = PrefUtils.getInstance(this, this.getString(R.string.ownerPref));
			telNo = prefUtils.getString(this.getString(R.string.savedTelNo), "");
			aQuery.id(R.id.edit_telno).getEditText().setText(telNo);
			password = prefUtils.getString(this.getString(R.string.savedPassword), "");
			aQuery.id(R.id.edit_password).getEditText().setText(password);
		}
		
		AppUtils.popupSoftKeyboard(this);
	}
	
	@Override
	public void onStop() {
		info("LoginActivity: onStop");
		super.onStop();
	}


	@Override
	protected int getLayoutId() {
		// TODO Auto-generated method stub
		return R.layout.activity_login;
	}

	@Override
	protected void onTitleInit() {
		// TODO Auto-generated method stub
		initTitle(TITLE_BTN_EXIST,
				R.string.register,
				TITLE_BTN_EXIST,
				R.string.btn_login_forget,
				R.string.title_login);
	}
	
	public void onRightBtn(View v) {
		Intent intent = new Intent(this, PasswordRecoverActivity.class);
		intent.putExtra("mobile", aQuery.id(R.id.edit_telno).getText().toString());
		startActivityForResult(intent, RECOVER_PASSWORD);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null) {
			if (requestCode == RECOVER_PASSWORD) {
				String mobile = data.getStringExtra("mobile");
				if (mobile != null) {
					aQuery.id(R.id.edit_telno).getTextView().setText(mobile);
				}
			}
		}
	}

	public void onLogin(View v) {
		saveUserChkPref();
		
		AsyncHttpResponseWithResultHandler responseHandler = new AsyncHttpResponseWithResultHandler(){

			@Override
			public void onResultSuccess(String response) {
				// TODO Auto-generated method stub
				super.onResultSuccess(response);
				JSONObject jsonObj = this.getBody(response);
				setLastVersionInfo(jsonObj);
				User user = assembleUser(jsonObj);
				if(user != null) {
					user.setTelNo(telNo);
					user.setPassword(password);
					setMe(user);
					
					PrefUtils prefUtils = PrefUtils.getInstance(LoginActivity.this, LoginActivity.this.getString(R.string.ownerPref));
					if(bSavePass) {
						prefUtils.addString(LoginActivity.this.getString(R.string.savedTelNo), telNo);
						prefUtils.addString(LoginActivity.this.getString(R.string.savedPassword), password);
					} else {
						prefUtils.remove(LoginActivity.this.getString(R.string.savedTelNo));
						prefUtils.remove(LoginActivity.this.getString(R.string.savedPassword));
					}

					Class<?> cls = getNextActivityByUserStatus(user);
					if (cls != null) {
						ShakeApplication.getShared().afterLogin(user);
						finish();
						go(cls);
					}

				} else {
					toast(R.string.err_login_failed);
				}
			}

			@Override
			public void onResultFailure(String result) {
				// TODO Auto-generated method stub
				super.onResultFailure(result);
				if (ResultCodeFactory.REQUEST_MOBILE_ERROR.equals(result)) {
					toast(R.string.err_telno_error);
				}
				else if (ResultCodeFactory.REQUEST_PASSWORD_ERROR.equals(result)) {
					toast(R.string.err_password_error);
				}
				else  {
					toast(R.string.err_login_failed);
				}
			}
			
			@Override
			public void onFailure(Throwable arg0, String arg1) {
				// TODO Auto-generated method stub
				super.onFailure(arg0, arg1);
				toast(R.string.err_network_issues);
			}
        	
        };
        
        telNo = aQuery.id(R.id.edit_telno).getText().toString();
        password = aQuery.id(R.id.edit_password).getText().toString();
        
        if(telNo == null || telNo.trim().length() == 0) {
        	toast(R.string.err_empty_telno);
        	return;
        }
        if(password == null || password.trim().length() == 0) {
        	toast(R.string.err_empty_password);
        	return;
        }
        
        Map<String, String> params = new HashMap<String, String>();
        params.put(NetUtils.MOBILE, telNo);
        params.put(NetUtils.PASSWORD, password);
        AsyncHttpClient client = NetUtils.login(this, responseHandler, params);
        if (client != null) {
        	showProgress(R.string.progress_login, client, responseHandler);
        }
	}
	
	private void saveUserChkPref() {
		bSavePass = aQuery.id(R.id.chk_save_password).getCheckBox().isChecked();
		bAutoLogin = aQuery.id(R.id.chk_auto_login).getCheckBox().isChecked();
		
		PrefUtils.getInstance(this, this.getString(R.string.registerPref))
			.addBoolean(this.getString(R.string.bSavePass), bSavePass)
			.addBoolean(this.getString(R.string.bAutoLogin), bAutoLogin);
	}
	
	public static void setLastVersionInfo(JSONObject jsonObj) {
		int lastVersionCode = jsonObj.optInt(NetUtils.VERSIONCODE, 0);
		if (lastVersionCode > 0) {
			ShakeApplication app = ShakeApplication.getShared();
			String lastVersionName = jsonObj.optString(NetUtils.VERSIONNAME);
			String updateUrl = jsonObj.optString(NetUtils.DOWNURL);
			app.lastVersionCode = lastVersionCode;
			app.lastVersionName = lastVersionName;
			app.updateUrl = updateUrl;
			app.checkUpdate = true;
		}
	}
	
	public static User assembleUser(JSONObject jsonObj) {
		if(jsonObj != null) {
			String token = jsonObj.optString(NetUtils.TOKEN);
			int sex = jsonObj.optInt(NetUtils.SEX, User.sex_unk);
			int status = jsonObj.optInt(NetUtils.STATUS, User.STATUS_BLOCK);
			String school = jsonObj.optString(NetUtils.SCHOOL);
			int job = jsonObj.optInt(NetUtils.JOB);
			String nickname = jsonObj.optString(NetUtils.NICKNAME);
			String strBirthday = jsonObj.optString(NetUtils.BIRTHDAY);
			Date birthday = null;
			if (strBirthday != null && !strBirthday.equals("")) {
				birthday = AppUtils.parseDate(strBirthday);
			}
			//JSONArray interest = jsonObj.optJSONArray(NetUtils.INTEREST);
			List<Integer> hobbies = new ArrayList<Integer>();
			String interest = jsonObj.optString(NetUtils.INTEREST);
			if (interest != null) {
				String[] interests = interest.split(",");
				for (int i = 0; i < interests.length; i++) {
					String is = interests[i];
					if (is != null) {
						is = is.trim();
						if (!is.equals("")) {
							try {
								int h = Integer.parseInt(is); 
								if(h != 0) {
									hobbies.add(h);
								}
							}
							catch(Exception e) {
							}
						}
					}
					
				}
			}
			String sign = jsonObj.optString(NetUtils.SIGN);
			String avatarUrl = jsonObj.optString(NetUtils.URL);
			int level = jsonObj.optInt(NetUtils.LEVEL, 0);
			String strCreatetime = jsonObj.optString(NetUtils.CREATETIME);
			Date createtime = AppUtils.parseDate(strCreatetime);
			User user = new User();
			user.setAuthToken(token);
			user.setNickname(nickname);
			user.setSex(sex);
			user.setStatus(status);
			user.setSchool(school);
			user.setJob(job);
			user.setSignature(sign);
			user.setHobbies(hobbies);
			user.setBirth(birthday);
			user.setAvatarUrl(avatarUrl);
			user.setLevel(level);
			user.setHasLogin(true);
			user.setRegDate(createtime);

			return user;
		}
		return null;
	}
	
	public static Class<?> getNextActivityByUserStatus(User user) {
		Class<?> ret = null;
		if (user.getNickname() == null 
				|| user.getNickname().equals("")) {
			ret = InputNicknameActivity.class;
		}
		else if (user.getBirth() == null) {
			ret = InputBirthdayActivity.class;
		}
		else if (user.getAvatarUrl() == null
				|| user.getAvatarUrl().equals("")) {
			ret = SetAvatarActivity.class;
		}
		else {
			ret = ShakeTabActivity.class;
		}
		//ret = SetAvatarActivity.class;
		return ret;
	}
	
	public void onCheck(View v) {
		if(v.getId() == R.id.chk_save_password) {
			
		}
		else if(v.getId() == R.id.chk_auto_login) {
			
		}
	}
	
	@Override
	public void onLeftBtn(View v) {
		super.onLeftBtn(v);
		go(MainActivity.class);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}
	
}
